module.exports = (app) => {
  const mongoose = app.mongoose;
  mongoose.pluralize(null);
  const Schema = mongoose.Schema;
  const RecommendGoodsSchema = new Schema(
    {
      cover: {
        type: String,
        require: true,
      },
      goodsId: {
        type: mongoose.Types.ObjectId,
        ref: "Goods",
        require: true,
      },
      categoryId: {
        type: mongoose.Types.ObjectId,
        ref: "Category",
        require: true,
      },
      // 访问次数
      visitTimes: {
        type: Number,
        default: 0
      },
      // 推荐日期
      recommendDate: {
        type: [Date],
        required: true,
      },
      // 销量增长
      saleIncr: {
        type: Number,
        default: 0
      },
      // 日均增长：
      dayAvgIncr: {
        type: Number,
        default: 0
      },
      // 排序
      sort: {
        type: Number,
        default: 0
      }
    },
    { versionKey: false, timestamps: true }
  );
  RecommendGoodsSchema.pre("save", function (next) {
    // 计算日均增长
    const oneDay = 24 * 60 * 60 * 1000; // 每天的毫秒数
    const durDays = Math.ceil((new Date().getTime() - this.recommendDate[0].getTime()) / oneDay);//持续天数
    this.dayAvgIncr = Number((this.saleIncr / durDays).toFixed(2));
    next();
  });

  return mongoose.model("RecommendGoods", RecommendGoodsSchema);
};
